package org.dromara.web.mock;

import cn.dev33.satoken.oauth2.consts.GrantType;
import cn.dev33.satoken.oauth2.data.loader.SaOAuth2DataLoader;
import cn.dev33.satoken.oauth2.data.model.loader.SaClientModel;
import lombok.RequiredArgsConstructor;
import org.dromara.application.domain.vo.AppUserVo;
import org.dromara.application.domain.vo.ApplicationVo;
import org.dromara.application.service.IAppUserService;
import org.dromara.application.service.IApplicationService;
import org.dromara.common.core.utils.OpenIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Sa-Token OAuth2：自定义数据加载器
 *
 * @author click33
 */
@Component
@RequiredArgsConstructor
public class SaOAuth2DataLoaderImpl implements SaOAuth2DataLoader {

    private final IApplicationService applicationService;
    private final IAppUserService appUserService;

	// 根据 clientId 获取 Client 信息
	@Override
	public SaClientModel getClientModel(String clientId) {
		// 此为模拟数据，真实环境需要从数据库查询
        ApplicationVo application = applicationService.getByClientId(clientId);
        return new SaClientModel()
            .setClientId(application.getClientId())
            .setClientSecret(application.getClientSecret())
            .addAllowRedirectUris(application.getWhitelist())
            .addContractScopes("openid", "unionid", "userid", "userinfo", "oidc")
            .addAllowGrantTypes( // 所有允许的授权模式
                GrantType.authorization_code, // 授权码式
                GrantType.implicit,  // 隐式式
                GrantType.refresh_token,  // 刷新令牌
                GrantType.password,  // 密码式
                GrantType.client_credentials  // 客户端模式
            );
	}

	// 根据 clientId 和 loginId 获取 openid
	@Override
	public String getOpenid(String clientId, Object loginId) {
		// 此处使用框架默认算法生成 openid，真实项目建议改为从数据库查询
        AppUserVo byClientIdAndLoginId = appUserService.getByClientIdAndLoginId(clientId, Long.parseLong(loginId.toString()));
        return byClientIdAndLoginId == null ? null : byClientIdAndLoginId.getOpenId();
	}

}
